<?php

abstract Class CmsCategoriesController extends AppController
{
	var $helpers = array('Form','Html','Cms.Index');
	protected $categoryModelAlias;
	protected $displayName;
	var $abstractView = "Categories.Categories";
	function beforeFilter()
	{
		$this->categoryModelAlias = $this->{$this->modelNames[0]}->alias;	
		$this->displayName = $this->categoryModelAlias;
		parent::beforeFilter();
	}
	function admin_add()
	{
		if($this->data)
		{
			if($this->_add($this->data))
			{
				$this->successMsg(sprintf(__("%s has been added."),$this->displayName));
				
				$this->redirect(array('action'=>"index"));
			}else
			{
				$this->errorMsg(sprintf(__("%s cannot be saved. Please try again"),$this->displayName));
			}	
		}
	}
	
	protected  function getCategoryModel()
	{
		return $this->{$this->categoryModelAlias};
	}
	
	function _add($data,$id = null)
	{
		$this->getCategoryModel()->create();
		if($id)
		{
			$this->getCategoryModel()->id = $id;
		}
		return $this->getCategoryModel()->save($data);
	}
	
	function admin_index()
	{
		$categories = $this->paginate();
		$this->set('categories',$categories);
	}
	
	function admin_view($id = null)
	{
		if (!$id) {
			$this->Session->setFlash(__('Invalid Category.', true));
			$this->redirect(array('action'=>'admin_index'));
		}
		$this->set('category', $this->getCategoryModel()->read(null, $id));
		$categoryList = $this->getCategoryModel()->find('list');
		$this->set('categoryList',$categoryList);		
	}

	function admin_edit($id = null)
	{
		if (!$id && empty($this->data))
		{
			$this->errorMsg(__('Invalid Category.', true));
			$this->redirect(array('action'=>'admin_index'));
		}
		
		if (!empty($this->data))
		{
			$this->data[$this->categoryModelAlias]['id'] = $id;
			if ($this->_add($this->data))
			{
				$this->successMsg(__('The category has been saved.', true));
				$this->redirect(array('action'=>'admin_index'));
			} else {
				$this->errorMsg(__('The category could not be saved. Please, try again.', true));
			}
		}
		
		if (empty($this->data))
		{
			$this->data = $this->getCategoryModel()->read(null, $id);
		}		
	}

	function admin_delete($id = null)
	{
		if (!$id)
		{
			$this->errorMsg(__('Invalid URL!', true));
			$this->redirect(array('action'=>'admin_index'));
		}
		if ($this->getCategoryModel()->del($id))
		{
			$this->successMsg(__('category deleted.', true));
			$this->redirect(array('action'=>'admin_index'));
		}
	}
	
	function beforeRender()
	{
		$this->set(array('categoryModelAlias'=>$this->categoryModelAlias,'displayName'=>$this->displayName,'useTree'=>$this->getCategoryModel()->useTree()));
		parent::beforeRender();
	}	
	

}
?>